package com.linjacy.httpproject.component;


import com.linjacy.httpproject.annotation.MyRequestMapping;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

@Component
public class MyBootContentScanHandler {

    private static Set<Class> controllerSet = new HashSet<>();
    private static Map<String, Method> requestMappingMap = new HashMap<>();

    public MyBootContentScanHandler(){}

    /**
     *  初始化方法，在这里扫描Controller跟RequestMapping
     */
    @SneakyThrows
    public static void init(){
        //扫描Controller的类，并且加入到controllerSet
        ScanController("com.linjacy.httpproject.testMyAnnotationController");
    }

    public static Method getTheInvokeMethod(String path){
        return requestMappingMap.get(path);
    }

    private static void ScanController(String controllerPath) throws IOException, ClassNotFoundException {
        Enumeration<URL> controllerResource = ClassLoader.getSystemResources(controllerPath.replace(".", "/"));
        while(controllerResource.hasMoreElements()){
            URL url = controllerResource.nextElement();
            File packagePath = new File(url.getPath());
            //判断是否为路径
            if (packagePath.isDirectory()) {
                //获取路径下的所有controller类
                String[] files = packagePath.list();
                for (String fileName : files) {
                    //把.class的后缀去除
                    String className = fileName.substring(0, fileName.lastIndexOf('.'));
                    String fullClassName = String.format("%s.%s", controllerPath, className);
                    controllerSet.add(Class.forName(fullClassName));
                }
            }
        }
        ScanRequestMapping();
    }



    private static void ScanRequestMapping() {

        if(controllerSet.size() <= 0) return;

        controllerSet.forEach(aClass -> {
            //获取类上的requestMapping注解
            MyRequestMapping typeAnnotation = (MyRequestMapping) aClass.getAnnotation(MyRequestMapping.class);
            String typePathValue = typeAnnotation.value();
            //获取该Controller中的所有方法
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method method : declaredMethods) {
                MyRequestMapping methodAnnotation = method.getAnnotation(MyRequestMapping.class);
                if(methodAnnotation == null) continue;
                String finalValue = "/linjacy/" + typePathValue + methodAnnotation.value();
                requestMappingMap.put(finalValue, method);
            }
        });
    }
}
